using System;
using System.Collections;
using System.Configuration;
using System.Xml;

namespace Pitoshka.Tools.Helpers
{
	public class CachedXmlDocuments
	{
		private class XmlWithDateTime
		{
			public DateTime timeStamp;
			public XmlDocument doc;
		}

		private static Hashtable storedData = new Hashtable();

		public static XmlDocument GetXmlDocument(string key)
		{
			
			if (key == null)
				throw new System.ArgumentNullException("Key");
			string fileName = ConfigurationManager.AppSettings[key];
			if (fileName == null)
				throw new System.ArgumentException("AppSettings not found. ", "Key " + key);
			fileName = System.Web.HttpContext.Current.Server.MapPath(fileName);
			DateTime stamp = (new System.IO.FileInfo(fileName)).LastWriteTime;
			if (storedData[key] == null || ((XmlWithDateTime)storedData[key]).timeStamp != stamp)
			{
				lock (storedData.SyncRoot)
				{
					if (storedData[key] == null || ((XmlWithDateTime)storedData[key]).timeStamp != stamp)
					{
						XmlWithDateTime docAndStamp = new XmlWithDateTime();
						docAndStamp.doc = new XmlDocument();
						docAndStamp.doc.Load(fileName);
						docAndStamp.timeStamp = stamp;
						storedData[key] = docAndStamp;
					}
				}
			}
			return ((XmlWithDateTime)storedData[key]).doc;
		}
	}
}